package com.test.common;

import java.io.Serializable;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import msg.chestionar.ejb.bi.UserBI;

import com.msg.chestionar.to.UtilizatorTO;

@ManagedBean(name = "loginBean")
@SessionScoped
public class LoginBean implements Serializable {

	private static final long serialVersionUID = -4759076671753497857L;

	private String username;

	private String passwort;

	private int tip;

	@EJB
	private UserBI userBI;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPasswort() {
		return passwort;
	}

	public void setPasswort(String passwort) {
		this.passwort = passwort;
	}
	
	public int getTip() {
		return tip;
	}
	
	public String logout() {
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
		.getExternalContext().getSession(true);
		session.invalidate();
		return "login";
	}
	
	public String login() {

		UtilizatorTO user = userBI.getUser(this.username, this.passwort);

		HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
				.getExternalContext().getSession(true);

		FacesContext facesContext = FacesContext.getCurrentInstance();
		Locale locale = facesContext.getViewRoot().getLocale();
		ResourceBundle rb = ResourceBundle.getBundle("prop.messages", locale);

		if (user == null) {
			FacesMessage msg = new FacesMessage(rb
					.getString("login.loginFailed"));
			msg.setSeverity(FacesMessage.SEVERITY_ERROR);
			FacesContext.getCurrentInstance().addMessage(null, msg);
			return null;
		}

		int tip = user.getTip();
		boolean activ = user.getActiv();
		
		if (activ == false) {
			FacesMessage msg = new FacesMessage(rb
					.getString("login.inactiveUser"));
			msg.setSeverity(FacesMessage.SEVERITY_ERROR);
			FacesContext.getCurrentInstance().addMessage(null, msg);
			return null;
		} 
		
		session.setAttribute("loggedInUser", user);
		
		if (tip == 1) {
			session.setAttribute("autadmin", true);
			return "administrator";
		} else {
			session.setAttribute("autuser", true);

			return "user";
		}

	}

}
